import Vue from "vue";
import Vuex from "vuex";

const cartKey = "$cart";
Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        cart: JSON.parse(localStorage.getItem(cartKey) || "[]"),
    },

    mutations: {
        addCart(state, info) {
            let flag = false;
            state.cart.some(item => {
                if(item.id === info.id) {
                    item.count += parseInt(info.count);
                    flag = true;
                    return true;
                }
            });

            if(!flag) {
                // 购物车里没有该商品，直接添加到购物车
                state.cart.push(info);
            }
            localStorage.setItem(cartKey, JSON.stringify(state.cart));
        },

        // 修改购物车商品数量
        updateCartInfo(state, info) {
            console.log("info", info, state.cart);
            let carts = state.cart;
            let index = state.cart.findIndex(item => {
                return item.id === info.id;
            })
            // 修改购物车中商品的数量值
            carts[index].count = info.count;
            localStorage.setItem(cartKey, JSON.stringify(carts));
        },

        // 从购物车中移除指定商品
        removeCartByID(state, id) {
            state.cart.some((item, i) => {
                if(item.id === id) {
                    // 删除
                    state.cart.splice(i, 1);
                    return true;
                }
            });
            localStorage.setItem(cartKey, JSON.stringify(state.cart));
        },

        // 更新购物车中指定商品的选中状态
        updateCartSelected(state, info) {
            state.cart.some(item => {
                if (item.id === info.id) {
                    item.selected = info.selected;
                }
            });
            localStorage.setItem(cartKey, JSON.stringify(state.cart));
        }
    },

    getters: {

        // 计算所有商品籹
        getCartAllCount(state) {
            let count = 0;
            state.cart.forEach(item => {
                count += item.count;
            });
            return count;
        },

        getGoodsCount(state) {
            const obj = {};
            state.cart.forEach(item => {
                obj[item.id] = item.count;
            });
            return obj;
        },

        // 获取购物车中所有商品的选中状态
        getCartSelected(state) {
            const obj = {};
            state.cart.forEach(item => {
                obj[item.id] = item.selected;
            });
            return obj;
        },

        // 获取选中商品的数量和金额
        getCartCountAndAmount(state) {
            let obj = {
                // 选中的数量
                count: 0,
                // 总价
                amount: 0
            }
            state.cart.forEach(item => {
                if(item.selected) {
                    obj.count += item.count;
                    obj.amount += item.price * item.count;
                }
            });
            return obj;
        }
    }
})

export default store;